<?php

namespace App\Http\Controllers;

use App\Common\SDK\Facade\ZhiLing;
use App\Models\SmsLog;
use App\Services\Captcha;
use Carbon\Carbon;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;

class CaptchaController extends Controller
{
    public function getPicCaptcha()
    {
        $captcha = (new CaptchaBuilder())->build();

        $uuid = Str::uuid()->toString();
        Redis::setex('captcha:' . $uuid, 60, $captcha->getPhrase());

        return $this->response->array([
            'image' => base64_encode($captcha->get()),
            'uuid' => $uuid,
            'expire' => 60
        ]);
    }

    public function getSmsCaptcha(Request $request)
    {
        if ($request->get('action', '') === 'forget_password') {
            validator($request->all(), ['phone' => 'exists:agents,phone'], ['phone.exists' => '账号不存在'])->validate();
        }
        if (($captcha = Redis::get('captcha:' . $request->get('uuid'))) === null
            || strtolower($captcha) !== strtolower($request->get('pic_captcha'))) {
            $this->response->errorBadRequest('图片验证码错误或者已过期');
        }
        if ($request->get('action', '') === 'reset_phone') {
            // 重设手机号时,获取当前用户手机号,不能还是老的手机号
            if (((\Auth::guard('h5')->user())['phone'] ?? '') === $request->get('phone')) {
                abort(400, '请不要使用当前账户的手机号');
            }
            // 不在这里验证是否别的账户在使用手机号,防止撞用户
        }

        $uuid = '';
        $expiredAt = 0;
        try {
            DB::beginTransaction();

            $phone = $request->get('phone');
            $code = random_int(100000, 999999);
            $uuid = Str::uuid();
            $content = sprintf('您的验证码是%d', $code);
            $expiredAt = Carbon::now()->addMinutes(15)->timestamp;
            SmsLog::create([
                'phone' => $phone,
                'content' => $content,
                'properties' => [
                    'code' => $code,
                    'expired_at' => $expiredAt,
                    'uuid' => $uuid,
                ],
                'type' => SmsLog::TYPE_CAPTCHA,
            ]);

            ZhiLing::sms([
                'phones' => $phone,
                'sms_body' => $content,
                'sms_sign' => env('ZHI_LING_SMS_SIGN', '省到家'),
            ]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            $this->response->errorBadRequest($e->getMessage());
        }

        return $this->response->created(null, [
            'uuid' => $uuid,
            'expired_at' => $expiredAt
        ]);
    }

    public function verificationSmsCaptcha(Request $request)
    {
        if (!Captcha::verificationSmsCaptcha($request)) {
            $this->response->errorBadRequest('短信验证码错误或者已过期');
        }

        return $this->response->accepted();
    }
}
